from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from myapp.models import Press,Author,Book
from myapp.serializers import PressSet,AuthorSet,BookSet


# 获取所有的出版社：
class PressView(APIView):
    def get(self,request):
#         获取出版社所有数据：
        chu_data = Press.objects.all()
#         序列化：
        ser = PressSet(chu_data,many=True)
#       返回数据：
        return Response(ser.data)


# 根据出版社获取对应的图书：
class BooksView(APIView):
    def get(self,request):
#         获取前端传递过来的出版社id：
        chu_id = request.query_params.get('chu_id')
#         根据出版社id获取对应的后端出版社：
        try:
            chu_idd = Press.objects.get(id=chu_id)
        except Exception as e:
            print(e)
            return Response({'msg':'数据不存在！','code':404})
#         根据出版社id获取对应的图书数据：
        book_data = chu_idd.book_set.all()
#         进行序列化：
        ser = BookSet(book_data,many=True)
#         返回数据：
        return Response(ser.data)


# 添加数据：
class AddBooks(APIView):
    def post(self,request):
#         获取前端传递的数据：
        book_name = request.data.get('book_name')
        price = request.data.get('price')
        count = request.data.get('count')
        author_id = request.data.get('author_id')
        press_id = request.data.get('press_id')

#     判断数据是否齐全：
        if not all([book_name,price,count,author_id,press_id]):
            return Response({'msg':'数据不齐全！','code':404})

#         判断数据是否存在：
        if Book.objects.filter(book_name=book_name):
            return Response({'msg':'数据已存在','code':404})

#         如果不存在就添加数据：
        try:
            Book.objects.create(
                book_name=book_name,
                price=price,
                count=count,
                author_id=author_id,
                press_id=press_id,
            )
        except Exception as e:
            print(e)
            return Response({'msg':'添加数据失败！','code':404})
        return Response({'msg':'添加数据成功','code':200})


# 后端获取前端的id：
class DelBooks(APIView):
    def delete(self,request):
        del_id = request.data.get('id')
#           根据前端id找到对应的数据删除：
        try:
            Book.objects.get(id=del_id).delete()
        except Exception as e:
            print(e)
            return Response({'msg':'删除失败！','code':404})
        return Response({'msg':'删除成功','code':200})



# 获取所有的作者：
class ZuoZhe(APIView):
    def get(self,request):
        atu = Author.objects.all()
#         序列化：
        ser = AuthorSet(atu,many=True)
#         返回：
        return Response(ser.data)



# 获取所有的出版社：
class ChuBan(APIView):
    def get(self):
        pro_data = Press.objects.all()
        ser = PressSet(pro_data,many=True)
        return Response(ser.data)





